<template>
	<view class="login">
		<view class="logo">
			<image :src="imgHost+'/static/images/bjy-logo.png'" mode="aspectFill"></image>
		</view>

		<up-form class="form" :model="form" :rules="rules" ref="uFormRef">
			<u-radio-group :modelValue="defaultRole" @change="changeRole">
				<u-radio v-for="(item,index) in roleList" :key="index" :name="item.value" :label="item.text"
					shape="circle" :disabled="item.disabled"></u-radio>
			</u-radio-group>

			<u-form-item label="手机号" label-width="60" prop="mobile">
				<u-input v-model="form.mobile" placeholder="请输入手机号" type="number"></u-input>
			</u-form-item>

			<u-form-item label="密码" label-width="60" prop="password" v-if="form.isSms == 0">
				<u-input v-model="form.password" placeholder="请输入密码" type="password"></u-input>
			</u-form-item>

			<u-form-item label="验证码" label-width="60" prop="verify_code" v-if="form.isSms == 1">
				<u-input v-model="form.verify_code" placeholder="请输入验证码">
					<template #suffix>
						<up-code ref="uCodeRef" @change="codeChange" :seconds="seconds" changeText="X秒后重新获取"></up-code>
						<up-button @tap="getCode" :text="tips" type="success" size="mini"></up-button>
					</template>
				</u-input>
			</u-form-item>

			<view class="protocol">
				<radio :checked="agreee" @click="setAgree()" />
				同意
				<text class="lk" @click="pageRoute('/pages/agreement/agreement?type=privacy')">《隐私协议》</text>
				和
				<text class="lk" v-if="defaultRole==='4'"
					@click="pageRoute('/pages/agreement/agreement?type=master')">《师傅协议》</text>
				<text class="lk" v-if="defaultRole==='3'"
					@click="pageRoute('/pages/agreement/agreement?type=agent')">《代理协议》</text>
				<text class="lk" v-if="defaultRole==='1' || defaultRole==='2'"
					@click="pageRoute('/pages/agreement/agreement?type=merchant')">《平台服务协议》</text>
				<text class="lk" v-if="defaultRole==='5'"
					@click="pageRoute('/pages/agreement/agreement?type=staff')">《员工协议》</text>
			</view>

			<view class="btn-wrap">
				<u-button type="primary" @click="submit">登录</u-button>
			</view>

			<view class="other-operat">
				<view class="login-type">
					<view class="lk" @click="setSms(1)" v-if="form.isSms == 0">账号密码登录</view>
					<view class="lk" @click="setSms(0)" v-if="form.isSms == 1">手机验证码登录</view>
				</view>
				<view class="forget" @click="pageRoute('/pages/forget-pass/forget-pass?role='+defaultRole)">忘记密码？</view>
			</view>
		</up-form>

		<gyd-upgrade-app ref="upgradeAppRef"></gyd-upgrade-app>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';

	const uFormRef = ref(null);
	const uCodeRef = ref(null);
	const upgradeAppRef = ref(null);

	const state = reactive({
		title: '登录',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		roleList: [{
				text: '师傅',
				value: '4',
				disabled: false,
			},
			{
				text: '代理',
				value: '3',
				disabled: false,
			},
			{
				text: '商户',
				value: '1',
				disabled: false,
			},
			/* {
				text: '门店',
				value: '2',
				disabled: true,
			},
			{
				text: '员工',
				value: '5',
				disabled: true,
			} */
		],
		defaultRole: '4',
		agreee: false,
		form: {
			mobile: '',
			password: '',
			verify_code: '',
			isSms: 0,
		},
		seconds: 60,
		tips: '获取验证码',
		rules: {
			mobile: [{
					type: 'string',
					required: true,
					message: '请输入手机号',
					trigger: ['blur', 'change'],
				},
				{
					// 自定义验证函数，见上说明
					validator: (rule, value, callback) => {
						// 上面有说，返回true表示校验通过，返回false表示不通过
						// uni.$u.test.mobile()就是返回true或者false的
						return uni.$u.test.mobile(value);
					},
					message: '手机号码不正确',
					// 触发器可以同时用blur和change
					trigger: ['change', 'blur'],
				}
			],
			'verify_code': {
				type: 'string',
				required: true,
				message: '请输入验证码',
				trigger: ['blur', 'change'],
			},
			password: [{
				type: 'string',
				required: true,
				message: '请输入密码',
				trigger: ['blur', 'change'],
			}, ],
		}
	});

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		const isRefreshing = cache.get('isRefreshing', false) || false;
		console.log('是否刷新页面', isRefreshing);
		if (isRefreshing) {
			cache.clear('isRefreshing');
			pageTabRoute('/pages/login/login');
		}
		cache.set('role', state.defaultRole);

		// #ifdef APP
		checkVersion();
		// #endif
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
	})

	onReachBottom(() => {
		console.log('触底加载更多');
	})

	//检查版本
	function checkVersion() {
		uni.getSystemInfo({
			success: (data) => {
				console.log('系统信息', data);
				request.get('index/getAppVersion', {
					version: data.appVersion,
					appType: 'manage',
					platformType: data.platform
				}).then(res => {
					console.log('获取更新', res);
					if (res.code == 1) {
						if (res.data.isUpdate) {
							console.log('需要更新', res.data.isUpdate);
							upgradeAppRef.value.open();
						}
					}
				})
			}
		})
	}

	function changeRole(e) {
		console.log('切换角色', e);
		cache.set('role', e);
		state.defaultRole = e;
	}

	function setAgree() {
		state.agreee = !state.agreee;
	}

	function setSms(type) {
		state.form.isSms = type;
	}

	function getCode() {
		if (uCodeRef.value.canGetCode) {
			// 向后端请求验证码
			uni.showLoading({
				title: '正在获取验证码',
			});
			request.get("login/smsSend", state.form).then(res => {
				console.log('获取验证码', res);
				if (res.code == 1) {
					setTimeout(() => {
						uni.hideLoading();
						// 这里此提示会被start()方法中的提示覆盖
						uni.$u.toast(res.msg);
						// 通知验证码组件内部开始倒计时
						uCodeRef.value.start();
					}, 2000);
				} else {
					util.showTip(res.msg);
				}
			})
		} else {
			uni.$u.toast('倒计时结束后再发送');
		}
	}

	const codeChange = (text) => {
		state.tips = text;
	};

	function submit() {
		uFormRef.value.validate().then(valid => {
			if (valid) {
				handleLogin();
			}
		}).catch(() => {
			// 处理验证错误  
			uni.$u.toast('校验错误');
		});
	}

	function handleLogin() {
		console.log('登录操作');
		if (!state.agreee) {
			util.showTip('请阅读并同意协议')
			return;
		}

		state.form.role = state.defaultRole;

		uni.showLoading();
		request.post("login/login", state.form).then(res => {
			console.log('登录结果', res);
			if (res.code == 1) {
				uni.showToast({
					icon: 'success',
					title: res.msg,
				})
				loginSussess(res.data);
			} else {
				uni.hideLoading();
				uni.showToast({
					icon: 'error',
					title: res.msg,
				})
			}
		}).catch(err => {
			console.log(err)
			uni.hideLoading();
			uni.showToast({
				icon: 'none',
				title: err.msg || '登录失败'
			})
		});
	}

	const loginSussess = (data) => {
		console.log('登录成功');
		uni.hideLoading();
		cache.set('selStore', data.store);
		// 保存角色
		cache.set('role', state.defaultRole);
		// 保存token
		util.setToken(data.token);
		// 保存登录用户
		util.setUserInfo(data.user);
		// 事件通知
		uni.$emit('login_success');
		// 延迟后，跳转页面
		setTimeout(function() {
			switch (state.defaultRole) {
				case '1':
					pageTabRoute('/merchantPages/index/index');
					break;
				case '2':
					pageTabRoute('/shopPages/index/index');
					break;
				case '3':
					pageTabRoute('/agentPages/index/index');
					break;
				case '4':
					pageTabRoute('/masterPages/index/index');
					break;
				case '5':
					pageTabRoute('/staffPages/index/index');
					break;
			}
		}, 800);
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		roleList,
		defaultRole,
		agreee,
		form,
		seconds,
		tips,
		rules,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		overflow: hidden;
		height: 100%;
		background-color: $u-bg-reverse-color;
	}

	.login {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 48rpx 48rpx 0;

		.logo {
			margin-top: 85rpx;
			padding-bottom: 50rpx;

			image {
				width: 400rpx;
				height: 400rpx;
			}
		}

		.form {
			.protocol {
				display: flex;
				align-items: center;
				margin-top: $m24;
				font-size: $font-24;
			}

			.btn-wrap {
				@include f-center($direction: column);
				margin-top: 60rpx;
			}
		}

		.other-operat {
			display: flex;
			justify-content: space-between;
			margin: 30rpx 0;

			.login-type {
				.lk {
					margin-top: $m12;
					color: $primary-color;
				}
			}

			.forget {
				margin-top: $m12;
			}
		}
	}
</style>